package org.example.utils;


import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import   org.apache.http.HttpEntity;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {


    /**
     * @param url
     * @param params 带参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;
        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String)i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }
        String apiUrl = url + param;
        String result = null;
        //创建一个httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception var18) {
//            logger.info("httputil get error:" + var18.getMessage());
            var18.printStackTrace();
        } finally {
            if (httpClient != null) {
                //关闭流
                HttpClientUtils.closeQuietly(httpClient);
            }

//            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }

        return result;
    }

}
